package com.cyh.nio;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

//写数据
public class FileChannelDemo02 {
    public static void main(String[] args) throws IOException {
        RandomAccessFile aFile = new RandomAccessFile("D:\\cyh\\work_java\\TestNioOrIo\\src\\com\\cyh\\2.txt", "rw");
        FileChannel channel = aFile.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        String newData = "data cyh001";
        buffer.clear();

        //写buffer
        buffer.put(newData.getBytes());

        //切换成读buffer
        buffer.flip();

        while (buffer.hasRemaining()) {
            channel.write(buffer);

        }
        channel.close();
    }
}
